package com.jsj.servlet.ch3;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/HelloServlet3")
public class HelloServlet3 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public HelloServlet3() {
        super();
    }
    
    @Override
    public void init(ServletConfig config) throws ServletException {
    	super.init(config);
    	String username=config.getInitParameter("username");
    	String password=config.getInitParameter("password");    	
    	System.out.println("username===="+username+"\tpassword=="+password);
    	
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		//获取所有参数的名称
		//需要注意：如果在使用super.getServletContext()时报空指针，说明改写了该servlet的init方法，
		//这是应该在当前servlet中加入super.init(config);
		//如果没有该写过init方法，则不需要
		Enumeration<String> paramsName=super.getServletContext().getInitParameterNames();
		//通过参数名获取参数的值		
		String sitename=super.getServletContext().getInitParameter("sitename");
		String developer=super.getServletContext().getInitParameter("developer");
		System.out.println("sitename==="+sitename+"\tdeveloper="+developer);
		
		while(paramsName.hasMoreElements()) {
			String name=paramsName.nextElement();
			System.out.println(name);
		}
		
		ServletContext context=super.getServletContext();
		context.setAttribute("author", "Tom");
		Integer count=(Integer) context.getAttribute("count");
		if(count==null) {
			count=1;
		}else {
			count=count+1;
		}
		context.setAttribute("count", count);
		PrintWriter out=response.getWriter();
		out.println("网站访问次数："+count);
		
		System.out.println("=========================获取应用信息=====================");
		System.out.println(context.getContextPath());
		System.out.println(context.getRealPath("/a/b/a.png"));
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
